var loginApp = angular.module('loginApp', []);
loginApp.controller('loginController', ['$scope', '$http', function ($scope, $http) {
    $scope.user = {};
    $scope.verifications = 0;//验证次数
    $scope.errorTip = '';
    $scope.login = function () {
        if($scope.user.username==null || $scope.user.username==''){
            $scope.errorTip = '用户名不能为空！';
            $('input:eq(0)').focus();
    		return;
    	}
        if($scope.user.password==null || $scope.user.password==''){
            $scope.errorTip = '密码不能为空！';
            $('input:eq(1)').focus();
            return;
        }
        if($scope.verifications >= 3){
            if(!$scope.validate()) return;
        }
        $scope.showLoad = true;
        var formData = $.param($scope.user);
        $http({
            method: 'POST',
            url: 'login.do',
            data: formData,
            headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).success(function (data) {
        	if (data.error) {
                $scope.errorTip = data.error;
                $scope.user.password = '';
                $('input:eq(1)').focus();
                $scope.showLoad=false;
                $scope.verifications++;
                if($scope.verifications >= 3){
                    $scope.createCode();//刷新验证码
                    $scope.codeInput = '';//清空文本框
                }
            }
            if (data.result == 'success') {
                window.location.href = 'main.do';
            }
        }).error(function () {
            $scope.errorTip = '请求服务器失败，请稍后再试！';
            window.location.href = 'login.do';
        });
      };


    //产生验证码
    $scope.createCode = function(){
        var code = '';
        var codeLength = 4;//验证码的长度
        var random = new Array(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R',
            'S','T','U','V','W','X','Y','Z');//随机数
        for(var i = 0; i < codeLength; i++) {//循环操作
            var index = Math.floor(Math.random()*36);//取得随机数的索引（0~35）
            code += random[index];//根据索引取得随机数加到code上
        }
        document.getElementById('codeBtn').value = code;
        $scope.codeBtn = code;//把code值赋给验证码
    }

    //校验验证码
     $scope.validate = function(){
        if($scope.codeInput == null || $scope.codeInput.length == 0) { //若输入的验证码长度为0
            $scope.errorTip = '验证码不能为空！'; //则弹出请输入验证码
            $('input:eq(2)').focus();
            return false;
        }
        else if($scope.codeBtn != $scope.codeInput.toUpperCase()) { //若输入的验证码与产生的验证码不一致时
            $scope.errorTip = '验证码错误，请重新输入！'; //则弹出验证码输入错误
            $scope.createCode();//刷新验证码
            $scope.codeInput = '';//清空文本框
            $('input:eq(2)').focus();
            return false;
        }
        return true;
    }
}]);